package com.lanhai.longheng.listener;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
  
import com.lanhai.longheng.dispatch.DispatchHack; 
import com.lanhai.longheng.utils.Tools;

@Component
public class HackListener {
	@Autowired 
	DispatchHack hack;
	  
	private boolean running;
	private Thread th;
	
	 private static final Logger logger =  LogManager.getLogger("agvlog");
		
		
	
	public void Start( ) {
		running=true; 
		th=new Thread() { 
			@Override
			public void run() {
				try{ 
					DatagramSocket	ds = new DatagramSocket(8013);
					while(running){
						byte data[] = new byte[20];
						DatagramPacket dp = new DatagramPacket(data, data.length);
						ds.receive(dp);
					 
						if(data.length<5) continue;
						
						int id=Tools.toIntL(new byte[] {data[1],data[2],data[3],data[4]}); 
						byte type=data[0];
						if(type==1) {
							//释放交管
							logger.info("后台发送指令：释放交管：id="+id);
							hack.releaseControllerArea(id);
						}else if(type==2) {
							//释放机台
							logger.info("后台发送指令：释放机台：id="+id);
							hack.releaseDevice(id);
						}else if(type==3) {
							//重置交管区数据
							logger.info("后台发送指令：重置交管区数据");
							hack.reloadControllerArea();
						}else if(type==4) {
							//重置点位数据
							logger.info("后台发送指令：重置点位数据");
							hack.reloadDot( );
						}else if(type==5) {
							//释放充电桩
							logger.info("后台发送指令：释放充电桩:id="+id);
							hack.releasePower(id );
						}else if(type==6) {
							//填充机台装料
							logger.info("后台发送指令：填充机台装料:id="+id);
							hack.fullDeviceMount(id );
						}else if(type==7) {
							//清空机台装料
							logger.info("后台发送指令：清空机台装料:id="+id);
							hack.emptyDeviceMount(id ); 
						}else if(type==8) {
							if(id==1) {
								logger.info("后台发送指令：清空制绒缓存机窄路" );
								hack.releaseZR(); 
							}else if(id==2) {
								logger.info("后台发送指令：清空扩散SE窄路" );
								hack.releaseKS(); 
							}
						}else if(type==9) {
							//清空机台装料
							logger.info("后台发送指令：清空agv状态:id="+id);
							hack.releaseAgv(id );  
						}
						 
						 
					}	
					ds.close();
				}catch(Exception e){
					e.printStackTrace();
				}	
			}
			
		};
		th.start();
	}
	 
	
	public void Stop() {
		running=false;
		try {
			th.interrupt();
			th=null; 
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}
